import React from "react";
import { FlatList, StyleSheet, Text } from "react-native";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import navigator from "../../utils/navigator";
import BasePage from "../BasePage";
import ListSeparator from "../common/ListSeparator";
import ListEmpty from "../common/ListEmpty";
import ListFooter from "../common/ListFooter";
import DateFilter from "../components/DateFilter";
import { inject, observer } from "mobx-react";
import moment from "moment";
import Events from "../../utils/events";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import { Icon } from "../components";
import PickerTypeDialog from "../common/PickerTypeDialog";
import { setClipboardContent, uploadError } from "../../utils/util";
const pickerData = ["全部", "未申诉", "申诉成功", "申诉失败"];
import { listOrderTimeOut } from "../../net/order";

/**
 * 超时订单
 */
@inject("userStore", "appStore")
@observer
export default class TimeoutOrder extends BasePage {

  constructor(props) {
    super(props);
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: moment().format("YYYY-MM-DD"),
      ratioTimeOut: "0%",
      countTimeOut: 0,
      count: 0,
      selectType:0,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData(true);
    this.refreshOrderList = Events.subscribe("RefreshTimeOutOrderList", () => this._renderRefresh(false));
  }

  componentWillUnmount() {
    super.componentWillUnmount();
    this.refreshOrderList && this.refreshOrderList.remove();
  }


  loadData = (showLoading = false) => {
    const { dataList, delyStartTime, delyEndTimeEnd,selectType } = this.state;
    const { userInfo } = this.props.userStore;
    const ordStates=['',-1,2,3]
    this.isLoading = true;
    if(IsNullOrEmpty(delyStartTime))
    {
      uploadError('listOrderTimeOut查询日期为空',`${delyStartTime},${delyEndTimeEnd}`)
    }
    let params = {
      // pageNum: this.pageNo,
      // pageSize: this.pageSize,
      token: global.token,
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
      ordState: ordStates[selectType],
    };
    listOrderTimeOut(params)
      .then(res => {
        this.isLoading = false;

        this.setState({
          dataList: res.list,
          ratioTimeOut: res.ratioTimeOut,
          countTimeOut: res.countTimeOut,
          count: res.count,
          isRefreshing: false,
          showEmpty: IsNullOrEmpty(res.list),
        });
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: false,
        });
      });
  };

  _onEndReached = async () => {
    //如果是正在加载中或到底了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (this.pageNo == this.totalPages || this.totalPages == 0) {
      return;
    } else {
      this.pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.loadData();
  };

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData(true);
    }
  };

  /**
   * //审批状态 1 申诉待处理 2同意申诉 3拒绝申诉 不存在代表未申诉
   * @param status
   * @returns {JSX.Element}
   */
  getOrderStatus = (item) => {
    switch (item.audit_state) {
      case 1:
        return (
          <View>
            <Text style={commonStyles.text_green_13}>申诉待处理</Text>
          </View>
        );
      case 3:
        return (
          <View>
            <Text style={commonStyles.text_red_13}>申诉失败</Text>
          </View>
        );
      case 2:
        return (
          <View>
            <Text style={commonStyles.text_green_13}>申诉成功</Text>
          </View>
        );
      default:
        return (
          <View>
            <Text style={commonStyles.text_blue_13}>申诉</Text>
          </View>
        );
    }
  };

  getAuditState = (audit_state) => {
    switch (audit_state) {
      case 1:
        return "待处理";
      case 2:
        return "申诉成功";
      case 3:
        return "申诉失败";
      default:
        return "未申诉";
    }
  };

  render_item = ({ item, index }) => {
    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(item?.xmbz_no)}>
            <Text style={commonStyles.text_black_14}>单号：{item?.xmbz_no}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>配送开始时间</Text>
            <Text
              style={commonStyles.text_blue_13}>{item.delivery_start_time ? moment(item.delivery_start_time).format("MM-DD HH:mm") : ""}</Text>
          </View><View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>配送终止时间</Text>
            <Text
              style={commonStyles.text_blue_13}>{item.delivery_end_time ? moment(item.delivery_end_time).format("MM-DD HH:mm") : ""}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>实际完成时间</Text>
            <Text
              style={commonStyles.text_black_13}>{item.received_time ? moment(item.received_time).format("MM-DD HH:mm") : ""}</Text>
          </View>

          <View style={{ ...styles.itemWrap, alignItems: "flex-start" }}>
            <Text style={commonStyles.text_black_13}>申诉理由</Text>
            <View marginL-20 flex right>
              <Text style={commonStyles.text_black_13}>{item.reason}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>申诉说明</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.explain}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>申诉状态</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{this.getOrderStatus(item)}</Text>
            </View>
          </View>

          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理状态</Text>
            <Text style={commonStyles.text_black_13}>{this.getAuditState(item.audit_state)}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>审核说明</Text>
            <Text style={commonStyles.text_black_13}>{item?.audit_text}</Text>
          </View>
        </View>
        {
          IsNullOrEmpty(item.audit_state) ?
            <View style={styles.line} /> : null
        }
        {
          IsNullOrEmpty(item.audit_state)&&item.datediff<=1 ?
            <View style={styles.reasonWrap}>
              <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn}
                                onPress={() => navigator.navigate("OrderAppeal", { xmbzNo: item.xmbz_no })}>
                <Text style={commonStyles.text_black}>我要申诉</Text>
              </TouchableOpacity>
            </View>
            : null
        }
      </View>
    );
  };

  renderHeader = () => {
    const { count, countTimeOut, ratioTimeOut } = this.state;
    return (
      <View marginH-15>
        <View marginB-10>
          <Text style={commonStyles.text_black}>您总共配送<Text style={{ color: "#4A90E2" }}>{count}</Text>单，超时<Text
            style={{ color: "#EC808D" }}>{countTimeOut}</Text>单，超时率<Text
            style={{ color: "#EC808D" }}>{ratioTimeOut}</Text></Text>
        </View>
      </View>
    );
  };

  render() {
    const { dataList, isRefreshing ,selectType} = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"超时订单"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          rightButton={ViewUtils.getRightImgTextBtn('reload1','',() => this._renderRefresh(false),16)}
        />
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter onQueryClick={(delyStartTime, delyEndTimeEnd) => this.setState({
              delyStartTime,
              delyEndTimeEnd,
            }, () => this._renderRefresh(false))} />

            <TouchableOpacity activeOpacity={1} style={styles.typeWrap} onPress={()=>this.pickerOrderTypeDialog.show(selectType,pickerData)}>
              <View marginR-3>
                <Text numberOfLines={1} style={commonStyles.text_black}>{pickerData[selectType]}</Text>
              </View>
              <Icon type="AntDesign" name="down" size={12} color={"#CCCCCC"} />
            </TouchableOpacity>

          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{ flexGrow: 1 }}
            keyExtractor={(item, index) => "menu_" + index}
            renderItem={this.render_item}
            ItemSeparatorComponent={() => <ListSeparator height={0.5} backgroundColor={"#F7F7F7"} />}
            ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
            // onEndReached={this._onEndReached}
            // onEndReachedThreshold={0.1}
            ListFooterComponent={() => <ListFooter showFoot={this.state.showFoot} page={this.pageNo} />}
            ListHeaderComponent={this.renderHeader}
          />
        </View>
        <PickerTypeDialog ref={r=>this.pickerOrderTypeDialog=r} onChecked={(selectType)=>this.setState({selectType},()=>this.loadData(true))}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    alignItems: "flex-end",
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  }
  , line: {
    height: 1,
    backgroundColor: "#EFEFEF",
    marginHorizontal: 15,
  },
  typeWrap: {
    flexDirection: "row",
    alignItems: "center",
    width: 90,
    height: 40,
    justifyContent: "space-between",
    borderRadius: 4,
    borderWidth: 1,
    borderColor: "#CCCCCC",
    paddingHorizontal: 10,
    backgroundColor: "white",
  },
  btn: {
    width: 80,
    height: 30,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
});
